package cn.fws.meap.community.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import cn.fws.meap.community.entity.*;
import cn.fws.meap.community.enums.ArticleTypeEnum;
import cn.fws.meap.community.enums.CollectionTypeEnum;
import cn.fws.meap.community.mapper.*;
import cn.fws.meap.community.entity.ProblemResources;
import cn.fws.meap.community.enums.DetailsTypeEnum;
import cn.fws.meap.community.mapper.ProblemResourcesMapper;
import cn.fws.meap.community.service.*;
import cn.fws.meap.community.vo.ArticleListVo;
import cn.fws.meap.community.vo.Details;
import cn.fws.meap.user.entity.Collect;
import cn.fws.meap.user.mapper.CollectMapper;
import cn.fws.meap.utils.QiNiuUtil;
import cn.fws.meap.community.enums.ResourcesTypeEnum;
import cn.fws.meap.system.constants.QiNiuParam;
import cn.fws.meap.user.entity.User;
import cn.fws.meap.user.mapper.UserMapper;
import cn.fws.meap.utils.articleUtil.ProblemResourceUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import cn.fws.framework.utils.ConvertUtils;
import cn.fws.framework.utils.StringUtils;
import cn.fws.framework.utils.UUIDUtils;
import cn.fws.meap.community.mapper.ArticleMapper;
import cn.fws.meap.community.entity.Article;
import org.springframework.transaction.annotation.Transactional;

/**
 * 文章 服务层实现
 *
 * @author chenkh
 * @date 2019-03-07
 */
@Service
@Transactional
public class ArticleServiceImpl implements IArticleService {

    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private IResourcesService resourcesService;
    @Autowired
    private ProblemResourcesMapper problemResourcesMapper;

    @Autowired
    private DetailsUtils<Article> detailsUtil;

    @Autowired
    private ResourcesMapper resourcesMapper;
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private IProblemResourcesService problemResourcesService;

    @Autowired
    private ICreationService creationService;

    @Autowired
    private IEvaluateService evaluateService;
    @Autowired
    private CollectMapper collectMapper;

    /**
     * 查询文章信息
     *
     * @param id 文章ID
     * @return 文章信息
     */
    @Override
    public Article selectById(String id) {
        return articleMapper.selectById(id);
    }

    /**
     * 查询文章列表
     *
     * @param hotArticle 文章信息
     * @return 文章集合
     */
    @Override
    public List<ArticleListVo> selectList(String hotArticle) {
        List<ArticleListVo> articleList = articleMapper.selectList(hotArticle);
        for (ArticleListVo articles : articleList) {

            articles.setArticleMsg(QiNiuUtil.getFileMsg(articles.getArticleMsg()));
        }
        //传入文章列表,返回文章详情列表
        return articleList;
    }


    @Override
    public List<Details<Article>> selectListNew() {
        List<Article> articleList = articleMapper.selectListNew();
        //传入文章列表,返回文章详情列表
        return getDetailsList(articleList);
    }


    /**
     * 新增文章
     *
     * @param article 文章信息
     * @return 结果
     */
    @Override
    public String insert(Article article) {
        String uuid = UUIDUtils.getUUID();
        article.setCreateTime(new java.util.Date());
        //设置主键
        article.setId(uuid);
        //给图片和封面图片添加七牛云地址
        String titleImg = QiNiuParam.IMG_URL+article.getTitleImg();
        article.setTitleImg((titleImg));
        System.out.println("添加地址之后————"+titleImg);
        //定义图片地址，资源id
        String articleImgAddress;
        //注意两个问题图像problem_img可能有多个地址要字符串切割，切割完成存到七牛云
        String articleImgs = article.getArticleImg();
        System.out.println("======="+articleImgs);
        if (StringUtils.isNotEmpty(articleImgs)) {			
        	String[] splitArticleImgs = articleImgs.split(",");
            System.out.println("字符串数组长度——"+splitArticleImgs.length);
        	//调用资源方法把地址存入到resources中  存入3个参数 【资源地址，资源类型，openid】
        	for (String articleImg : splitArticleImgs) {
                System.out.println("图片没加地址之前————"+articleImg);
                StringBuilder stringBuilder=new StringBuilder().append(QiNiuParam.IMG_URL).append(articleImg);

        		articleImgAddress=  resourcesService.addResources(stringBuilder.toString(),ResourcesTypeEnum.IMAGE.getCode(),article.getOpenid());
                System.out.println("图片资源地址————"+articleImgAddress);
        		//把多个资源表id和问题表id存入中间表
        		problemResourcesService.insert(articleImgAddress,uuid);
        	}
		}
        //问题内容article_msg存到七牛云中
        String articleMsgMsgResource = QiNiuUtil.uploadFile(QiNiuParam.MEAP_DOCUMENT, article.getArticleMsg());
        //问题内容存入资源表中
        System.out.println("文章id------:"+article.getOpenid());
        String problemMsgAddress = resourcesService.addResources(articleMsgMsgResource, ResourcesTypeEnum.TEXT.getCode(), article.getOpenid());

        //把资源表中的id存入到问题表中的内容字段
        article.setArticleMsg(problemMsgAddress);
        articleMapper.insert(article);


        //添加创作记录表
        Creation creation=new Creation();
        creation.setArticleId(uuid);
        creation.setArticleType(ArticleTypeEnum.ARTICLE.getCode());
        creation.setOpenid(article.getOpenid());
        System.out.println("创作记录表+++"+creation.toString());
        creationService.insert(creation);

      /*  CreationUtil creationUtil=new CreationUtil();
        creationUtil.addCreation(uuid,ArticleTypeEnum.ARTICLE.getCode(),article.getOpenid());*/
        return uuid;

    }

    /**
     * 修改文章
     *
     * @param article 文章信息
     * @return 结果
     */
    @Override
    public int update(Article article) {
        // 获取ID
        String articleId = article.getId();
        String openid = article.getOpenid();
        // 设置修改时间
        article.setUpdateTime(new Date());
        // 获取新的图片地址
        String newImgAddress = article.getArticleImg();
        // 获取新的封面地址
        String newTitleImgAddress = article.getTitleImg();
        //获取新的文本地址
        String newMsgAddress = article.getArticleMsg();
        //获取新的视频地址
        String newVideoAddress = article.getVideoId();
        //获取新的音频地址
        String newVoiceAddress = article.getVoiceId();

        // 覆盖七牛旧版的文档对象
        //获取旧文本
        String oldMsgId = articleMapper.getMsgIdById(articleId);
        String msgId = resourcesService.updateMsgResources(oldMsgId, openid, newMsgAddress, ResourcesTypeEnum.IMAGE.getCode());
        article.setArticleMsg(msgId);

        // 用新版封面替换旧版
        String oldTitleImgId = articleMapper.getTitleImgIdById(articleId);
        String titleImgId = resourcesService.updateMsgResources(oldTitleImgId, openid, newTitleImgAddress, ResourcesTypeEnum.IMAGE.getCode());
        article.setTitleImg(titleImgId);
        // 删除旧版关联的资源对象
        resourcesService.removeResources(articleId);
        article.setVideoId(resourcesService.saveOtMResource(newVideoAddress, openid, ResourcesTypeEnum.VIDEO.getCode()));
        article.setVoiceId(resourcesService.saveOtMResource(newVoiceAddress, openid, ResourcesTypeEnum.AUDIO.getCode()));
        article.setArticleImg(resourcesService.saveOtMResource(newImgAddress, openid, ResourcesTypeEnum.IMAGE.getCode()));
        // 将新版资源地址插入到资源表，并将id串存入对应字段
        article.setArticleImg(newImgAddress);
        article = resourcesService.saveArticleResource(article);

        // 将字段中id串取出并建立管理关系
        saveArticleResourcesToMidTable(article);
        return articleMapper.update(article);
    }

    /**
     * 删除文章对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteByIds(String ids) {
        return articleMapper.deleteByIds(ConvertUtils.toStrArray(ids));
    }

    /**
     * 保存文章资源关联关系
     *
     * @param article
     */
    @Override
    public void saveArticleResourcesToMidTable(Article article) {
        String articleId = article.getId();
        ArrayList<ProblemResources> problemResourcesList = new ArrayList<ProblemResources>();
        Date date = new Date();
        //保存文章----文章图片资源
        addProResToList(articleId, article.getArticleImg(), problemResourcesList, date);
        //保存文章----文章视频资源
        addProResToList(articleId, article.getVideoId(), problemResourcesList, date);
        //保存文章----文章音频资源
        addProResToList(articleId, article.getVoiceId(), problemResourcesList, date);
        problemResourcesMapper.insertList(problemResourcesList);
    }

    /**
     * 传入文章列表,返回文章详情列表
     *
     * @param articleList
     * @return
     */
    @Override
    public List<Details<Article>> getDetailsList(List<Article> articleList) {
        List<Details<Article>> detailsList = new ArrayList<>();
        for (Article art : articleList) {
            //获取文章ID
            String artId = art.getId();
            //获取openid
            String openid = art.getOpenid();
            Details<Article> details = detailsUtil.getDetails(artId, openid, DetailsTypeEnum.IS_ARTICLE.getCode());
            //把文章对象添加到details
            details.setT(art);
            //将details添加到集合
            detailsList.add(details);
        }
        return detailsList;

    }

    public void addProResToList(String articleId, String
            resIds, ArrayList<ProblemResources> problemResources, Date date) {
        if (StringUtils.isNotEmpty(resIds)) {
            ProblemResourceUtil.addProRes(articleId,resIds,problemResources,date);
        }
    }

    /**
     * 文章详情
     *
     * @return 结果
     */
    @Override
    public ArticleListVo getArticleDetails(String articleId,String openId) {
        List pictures = new ArrayList();
        List evaluatesPictures = new ArrayList();
        int count = 0;
        //文章详情
        ArticleListVo articleListVo = articleMapper.selectArticleDetailsById(articleId);
        String fileMsg = QiNiuUtil.getFileMsg(articleListVo.getArticleMsg());
        articleListVo.setArticleMsg(fileMsg);

        //根据文章id查询出所有图片资源地址
        List<Resources> resources1 = resourcesMapper.selectArticlePictures(articleId);
        for (Resources resources : resources1) {
            pictures.add(resources.getResAddress());
        }
        articleListVo.setPictures(pictures);


        //点赞头像,倒叙排序显示最新的4个头像
        List<User> evaluatePictrueList = userMapper.getEvaluatePictrueList(articleId);

        for (User user : evaluatePictrueList) {
            if (count >= 4) {
                break;
            }
            evaluatesPictures.add(user);
            count++;
        }
        articleListVo.setEvaluatesPictures(evaluatesPictures);

        Boolean evaluateStatusFlag = evaluateService.selectOpenId(openId,articleId);
        articleListVo.setEvaluateStatus(evaluateStatusFlag);

        Collect collect = collectMapper.selectByarticleIdAndOpenId(articleId, openId);
        if(StringUtils.isNull(collect)){
            articleListVo.setCollectStatus(CollectionTypeEnum.NO_COLLECTION.getCode());
        }else {
            articleListVo.setCollectStatus(CollectionTypeEnum.COLLECTION.getCode());
        }


        return articleListVo;


    }


}
